package biz

import (
	"context"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strconv"
	"strings"
)

type User struct {
}

func (u User) Shopping(ctx context.Context, client *http.Client, reqUrl string, userId uint32) (result string, err error) {
	if userId <= 0 {
		err = errors.New(fmt.Sprintf("error:userId can not be zero. \n"))
		return
	}
	if reqUrl == "" {
		err = errors.New(fmt.Sprintf("error:reqUrl can not be empty. \n"))
		return
	}

	formValues := url.Values{
		"userId":  {strconv.Itoa(int(userId))},
		"goodsId": {"1"},
		"count":   []string{strconv.Itoa(1)},
	}
	reader := strings.NewReader(formValues.Encode())

	req, err := http.NewRequest("POST", reqUrl, reader)
	if err != nil {
		fmt.Printf("new request failed, err:%v\n", err)
		return
	}
	// 我R。。。自定义http客服端使用New Request 一定要定义Header头否则解析不出来
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	req = req.WithContext(ctx)
	resp, err := client.Do(req)
	if err != nil {
		return
	}
	defer resp.Body.Close()
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return
	}
	result = fmt.Sprintf("response: %s \n", body)
	return
}
